﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;
using myOffice = Microsoft.Office.Interop;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using TpBaseObjects.Base;
using TpExtensions;
using TpBaseObjects.Objects;
using System.DirectoryServices.AccountManagement;
using TpTools.Properties;
using System.IO;
using TpTools.Forms;

using TpData.Manager;
using TpContracts;
using TpBaseObjects.Models;
using System.Reflection;
using System.Windows.Forms;
using TpBaseObjects.Models.BusinessCases;

namespace TpTools {

    public class Office {

        #region Members

        private const string errType = "Err";
        private const string logType = "Log";
        private const string logArea = "TpTools.Office";

        #endregion

        #region Allgemein

        public static bool CheckExcelFile(string fileName) {
            bool ret = true;
            if (!File.Exists(fileName)) {
                string msg = String.Format("Datei ({0} ist nicht vorhanden!", fileName);
                MessageBox.Show(msg, "TecOffice", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Tools.FileIsInUse(fileName)) {
                string msg = String.Format("Datei ({0} wird gerade verwendet und ist gesperrt!", fileName);
                MessageBox.Show(msg, "TecOffice", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return ret;
        }

        private static DateTime GetDatumBis() {
            DateTime dBis;
            if (DateTime.Today.Day < 16) {
                dBis = new DateTime(DateTime.Today.AddMonths(2).Year, DateTime.Today.AddMonths(2).Month, 1);
                dBis = dBis.AddDays(-1);
            } else {
                dBis = new DateTime(DateTime.Today.AddMonths(3).Year, DateTime.Today.AddMonths(3).Month, 1);
                dBis = dBis.AddDays(-1);
            }
            return dBis;
        }

        public static Organisation SearchOrganisation() {
            Organisation ret = new Organisation();
            OrganisationSearch myForm = new OrganisationSearch();
            myForm.ShowDialog();
            ret = myForm.MyCurrentModel;
            return ret;
        }

        public static string GetTitelName(int titelKey) {
            string ret = "";
            switch (titelKey) {
                case 1:
                    ret = "DDr.";
                    break;
                case 2:
                    ret = "Dipl.Ing.";
                    break;
                case 3:
                    ret = "Dkfm.";
                    break;
                case 4:
                    ret = "Dr.";
                    break;
                case 5:
                    ret = "Ing.";
                    break;
                case 6:
                    ret = "Mag.";
                    break;
                case 7:
                    ret = "MMag.";
                    break;
                
            }
            return ret;
        }

        public static string GetMaForAbrLief(string company) {

            string ret = "";
            if (company == "Gt") {
                ret = "Tz";
            }

            if (company == "Lc") {
                ret = "Gl";
            }

            if (company == "Na") {
                ret = "Pn";
            }
            return ret;
        }

        public static string GetProviderForAbrLief(string shortName) {
            string ret = "";
            if (shortName == "Hm") {
                ret = "Hörmann";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "To") {
                ret = "Tousek";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            if (shortName == "Al") {
                ret = "Alulux";
            }
            return ret;
        }

        #endregion

        #region EMail / Outlook

        public static myOffice.Outlook.Application GetOutlookApplication() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("OUTLOOK") > -1) {
                        return (myOffice.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                    }
                }
                return new myOffice.Outlook.Application();
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "GetOutlookApplication: " + ex.Message, true);
            }
            return null;
        }

        public static void SendEmail(string to, string subject, string msg) {
            SendEmail(to, "", "", subject, msg);
        }

        public static void SendEmail(string to, string cc, string subject, string msg) {
            SendEmail(to, cc, "", subject, msg);
        }

        public static void SendEmail(string to, string cc, string bcc, string subject, string msg) {
            myOffice.Outlook.Application olApp = Office.GetOutlookApplication();
            if (olApp != null) {
                myOffice.Outlook.MailItem m = olApp.CreateItem(myOffice.Outlook.OlItemType.olMailItem);
                m.To = to;
                if (cc != "") {
                    m.CC = cc;
                }
                if (bcc != "") {
                    m.BCC = bcc;
                }
                m.Subject = subject;
                m.Body = msg;
                m.BodyFormat = myOffice.Outlook.OlBodyFormat.olFormatHTML;
                ((myOffice.Outlook._MailItem)m).Send();
            }
        }

        #endregion

        #region Excel

        public static bool CheckLiquiIsOpen(string jj, string path) {
            bool ret = false;
            string fileName = Path.Combine(path + jj, "Liqui.xlsm");
            if (Tools.FileIsInUse(fileName) | (!File.Exists(fileName))) {
                ret = true;
            }
            return ret;
        }

        public static bool CheckArJJIsOpen(string jj, string path) {
            bool ret = false;
            string fileName = Path.Combine(path + jj, "Ar" + jj + ".xlsm");
            if (Tools.FileIsInUse(fileName) | (!File.Exists(fileName))) {
                ret = true;
            }
            return ret;
        }

        public static bool CheckUserFileExists(string userName, string filePath) {
            bool ret = true;
            string jj = DateTime.Now.Year.ToString().Right(2);
            string fileName = Path.Combine(filePath, userName + "le" + jj + ".xlsx");
            if (!File.Exists(fileName)) {
                ret = false;
            }
            return ret;
        }

        public static void CreateCalculationFile(string filename, BusinessCaseModel model, string user) {
            try {
                myOffice.Excel.Application exApp = GetExcelApplication();
                if (exApp.DefaultSaveFormat != XlFileFormat.xlOpenXMLWorkbookMacroEnabled) {
                    exApp.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbookMacroEnabled;
                }
                exApp.Workbooks.Add(Extensions.tpExcelCalculationTemplate);
                Workbook wb = exApp.ActiveWorkbook;

                Worksheet sh = wb.ActiveSheet;
                PlzOrt pl = CommonDataManager.LoadPlzOrt(model.ProjectEPLZ);
                CalculationSheet project = new CalculationSheet(sh);
                project.ProjectName = model.ProjectName;
                project.ProjectNumber = model.ProjectNumber;
                project.Distance = model.Distance;
                project.CustomerGroup = model.CustomerGroup;
                project.Street = model.ProjectAddress;
                project.ZipCode = pl.Plz;
                project.Town = pl.Ort;
                project.WriteJob("Systemerfassung", "Geschäftsfall", DateTime.Now, "Lf", Contracts.MyUser.LoginName.Trim(), 0, "", "");
                wb.SaveAs(filename, FileFormat: XlFileFormat.xlOpenXMLWorkbookMacroEnabled);
                exApp.Visible = true;
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "CreateCalculationFile: " + ex.Message, true);
            }
        }

        public static bool ExcelIsStarted() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("EXCEL") > -1) {
                        return true;
                    }
                }

            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "ExcelIsStarted: " + ex.Message, true);
            }
            return false;
        }

        public static void FormatRowAsSummaryRow(Range r1, bool lastRow) {
            r1.Interior.Pattern = 1;
            r1.Interior.ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            r1.Interior.ThemeColor = XlThemeColor.xlThemeColorLight2;
            r1.Interior.TintAndShade = -0.149998474074526;
            r1.Interior.PatternTintAndShade = 0;
            r1.Font.Bold = true;

            r1.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
            r1.Borders[XlBordersIndex.xlEdgeTop].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            r1.Borders[XlBordersIndex.xlEdgeTop].TintAndShade = 0;
            r1.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlHairline;

            r1.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            r1.Borders[XlBordersIndex.xlEdgeBottom].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            r1.Borders[XlBordersIndex.xlEdgeBottom].TintAndShade = 0;
            if (lastRow) {
                r1.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
            } else {
                r1.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlHairline;
            }
        }

        public static Range GetAeRow(Worksheet sh, string projektName, string projektBezeichnung, int startRow) {
            bool startRowSelect = false;
            while (startRowSelect == false & startRow < 10000) {
                Range row = sh.Rows[startRow];
                AeRow aeRow = new AeRow(row);
                if (aeRow.ProjektName == projektName & aeRow.ProjektBezeichnung == projektBezeichnung) {
                    return row;
                }
                startRow++;
            }
            return null;
        }

        public static Microsoft.Office.Interop.Excel.Application GetExcelApplication() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("EXCEL") > -1) {
                        return (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
                    }
                }
                return new Microsoft.Office.Interop.Excel.Application();
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "GetExcelApplication: " + ex.Message, true);
            }
            return null;
        }

        public static void OpenExcelFile(string fileName) {
            Microsoft.Office.Interop.Excel.Application exApp = GetExcelApplication();
            if (File.Exists(fileName)) {
                Workbook wb = exApp.Workbooks.Open(fileName);
                ((Microsoft.Office.Interop.Excel._Workbook)wb).Activate();
            } else {
                MessageBox.Show("Die angegebene Datei: (" + fileName + ") ist nicht vorhanden.", "Tec-Office", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            exApp.Visible = true;
            
        }

        public static bool WorkbookIsLoaded(Microsoft.Office.Interop.Excel.Application exApp, string wbName) {
            foreach (Workbook wb in exApp.Workbooks) {
                if (wb.Name == wbName) {
                    return true;
                }
            }
            return false;
        }

        public static void WriteInvoiceToLiqui(CashSaleModel model) {
            Workbook wb = null;
            string sheetName = "Ze";
            string fileName = Path.Combine(@"T:\Rewe\" + model.SaleDate.Year.ToString().Right(2) + @"\Liqui.xlsm");
            bool excelStarted = ExcelIsStarted();
            myOffice.Excel.Application exApp = Office.GetExcelApplication();

            try {
                if (Tools.FileIsInUse(fileName) | (!File.Exists(fileName))) {
                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToLiqui: " + fileName + " ist geöffnet oder nicht vorhanden!", true);
                    return;
                }


                if (exApp != null) {

                }

                wb = exApp.Workbooks.Open(fileName);

                if (!Tools.SheetsExists(wb, sheetName)) {
                    return;
                }

                Worksheet sh = wb.Sheets[sheetName];
                ProjektLiquiSheet liqui = new ProjektLiquiSheet(sh);
                int rowNumber = 0;
                rowNumber = liqui.GetNextFreeRowNumber();


                if (rowNumber == 0) {
                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToLiqui : rowNumber=0", true);
                    return;
                }

                myOffice.Excel.Range newRow = sh.Rows[rowNumber];
                ProjektLiquiRow lRow = new ProjektLiquiRow(newRow, true);

                lRow.RechnungsNummer = model.InvoiceNo;
                lRow.RechnungsDatum = model.SaleDate;
                lRow.Kunde = model.OrgName;
                if (model.UseDeliveryAddress) {
                    lRow.Rechnungsempfänger = model.DeliverName;
                }
                lRow.DebitorenKonto = "400 00";
                lRow.SummeBrutto = model.GrossPrice;

                lRow.Datum = Tools.NextGoodBusinessDay(DateTime.Now);
                lRow.Datum = Tools.GetNextDueDate(model.SaleDate);

                lRow.Firma = "Tp";
                lRow.Type = "Bv";
                lRow.Qu = 100.0;
                lRow.DiktatZeichen = TecUserDataManager.LoadTecUser(model.UserID).LoginName.Trim();

                myOffice.Excel.Range r1 = newRow.Cells[1, "X"];
                r1.FormulaR1C1 = "=R" + newRow.Row.ToString() + "C" + (r1.Column - 8).ToString() + "*R" + newRow.Row.ToString() + "C" + (r1.Column - 1).ToString() + "/100";

                r1 = newRow.Cells[1, "AC"];
                r1.FormulaR1C1 = "=R" + newRow.Row.ToString() + "C" + (r1.Column - 1).ToString() + "-R" + newRow.Row.ToString() + "C" + (r1.Column - 13).ToString();
                model.WriteToLiquiDate = DateTime.Now;

            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToLiqui: " + ex.Message, true);
            } finally {
                if (wb != null) {
                    wb.Save();
                    wb.Close();
                }
                if (!excelStarted) {
                    exApp.Quit();
                }
            }
        }

        public static void WriteInvoiceToBv(CashSaleModel model) {
            Workbook wb = null;
            string sheetNameAuftrag = "SuAu";
            string sheetNameProduct = "SuPd";
            bool weiter = false;
            int rowNumber = 0;
            int currentRow = 2;
            string fileName = Path.Combine(@"T:\Kund\" + model.SaleDate.Year.ToString().Right(2) + @"\Bv" + model.SaleDate.Year.ToString().Right(2) + "Da.xlsx");
            bool excelStarted = ExcelIsStarted();
            myOffice.Excel.Application exApp = Office.GetExcelApplication();

            try {
                if (Tools.FileIsInUse(fileName) | (!File.Exists(fileName))) {
                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToBv: " + fileName + " ist geöffnet oder nicht vorhanden!", true);
                    return;
                }

                wb = exApp.Workbooks.Open(fileName);
                Organisation org = OrganisationDataManager.LoadOrganisation(model.OrgKey);

                #region Auftrag

                if (!Tools.SheetsExists(wb, sheetNameAuftrag)) {
                    return;
                }

                Worksheet sh = wb.Sheets[sheetNameAuftrag];

                while (weiter == false) {
                    if (currentRow >= 2000) {
                        return;
                    }
                    Range r1 = sh.Cells[currentRow, "C"];
                    if (r1.Value == null) {
                        rowNumber = currentRow;
                        break;
                    }
                    currentRow++;
                }

                double sumRabatt = 0; double sumDB = 0; double sumCosts = 0; double sumTime = 0;
                foreach (CashSaleDetailsModel cdm in model.MyDetails) {
                    CashSaleProductsModel pm = CashSaleDataManager.LoadProduct(cdm.ProductID);
                    sumRabatt += cdm.Price * cdm.RabattPercent1 / 100;
                    sumRabatt += cdm.Price * cdm.RabattPercent2 / 100;
                    sumRabatt += cdm.RabattFix;

                    sumCosts += pm.CostPrice;
                    sumDB += pm.SalesPrice - pm.CostPrice;

                }

                foreach (JobObj job in model.MyJobDetails) {
                    sumTime += job.LeistungZeit;
                }

                Range r2 = sh.Cells[rowNumber, "C"];
                r2.Value = org.Prefix.AddSpace() + org.OrgName.AddSpace() + org.ZusätzeFW.AddSpace() + org.RechtsForm.AddSpace();

                r2 = sh.Cells[rowNumber, "D"];
                r2.Value = "Bv" + model.SaleDate.Year.ToString().Right(2);

                r2 = sh.Cells[rowNumber, "E"];
                r2.Value = org.Plz;

                r2 = sh.Cells[rowNumber, "F"];
                r2.Value = org.Ort;

                r2 = sh.Cells[rowNumber, "G"];
                r2.Value = org.Straße;

                r2 = sh.Cells[rowNumber, "H"];
                r2.Value = model.SaleDate.Date;

                r2 = sh.Cells[rowNumber, "N"];
                r2.Value = Contracts.MyUser.LoginName.Trim();

                r2 = sh.Cells[rowNumber, "S"];
                r2.Value = model.InvoiceNo;

                r2 = sh.Cells[rowNumber, "BH"];
                r2.Value = model.SalePrice;

                r2 = sh.Cells[rowNumber, "BI"];
                r2.Value = sumRabatt;

                r2 = sh.Cells[rowNumber, "BJ"];
                r2.Value = (sumRabatt != 0 ? sumRabatt / model.SalePrice * 100 : 0);

                r2 = sh.Cells[rowNumber, "BK"];
                r2.Value = model.SalePrice - sumRabatt;

                r2 = sh.Cells[rowNumber, "BL"];
                r2.Value = sumDB;

                r2 = sh.Cells[rowNumber, "BM"];
                r2.Value = sumDB / model.SalePrice * 100;

                r2 = sh.Cells[rowNumber, "BN"];
                r2.Value = sumTime;

                #endregion

                #region Product

                if (!Tools.SheetsExists(wb, sheetNameProduct)) {
                    return;
                }

                sh = wb.Sheets[sheetNameProduct];

                currentRow = 3;

                while (weiter == false) {
                    if (currentRow >= 2000) {
                        return;
                    }
                    Range r1 = sh.Cells[currentRow, "C"];
                    if (r1.Value == null) {
                        rowNumber = currentRow;
                        break;
                    }
                    currentRow++;
                }

                foreach (CashSaleDetailsModel cdm in model.MyDetails) {
                    if (cdm.ProductID == 0) {
                        continue;
                    }
                    CashSaleProductsModel pm = CashSaleDataManager.LoadProduct(cdm.ProductID);
                    if (pm.Unity == "Pa") {
                        continue;
                    }
                    
                    r2 = sh.Cells[rowNumber, "C"];
                    r2.Value = org.Prefix.AddSpace() + org.OrgName.AddSpace() + org.ZusätzeFW.AddSpace() + org.RechtsForm.AddSpace();

                    r2 = sh.Cells[rowNumber, "D"];
                    r2.Value = "Bv" + model.SaleDate.Year.ToString().Right(2);

                    r2 = sh.Cells[rowNumber, "E"];
                    r2.Value = org.Plz;

                    r2 = sh.Cells[rowNumber, "F"];
                    r2.Value = org.Ort;

                    r2 = sh.Cells[rowNumber, "G"];
                    r2.Value = org.Straße;

                    r2 = sh.Cells[rowNumber, "H"];
                    r2.Value = model.SaleDate.Date;

                    r2 = sh.Cells[rowNumber, "W"];
                    r2.Value = pm.CategorieShort;

                    r2 = sh.Cells[rowNumber, "X"];
                    r2.Value = pm.SubCategorieShort;

                    r2 = sh.Cells[rowNumber, "AB"];
                    r2.Value = pm.Manufacturer;

                    r2 = sh.Cells[rowNumber, "AD"];
                    r2.Value = pm.Provider;

                    r2 = sh.Cells[rowNumber, "AH"];
                    r2.Value = pm.ProductName;

                    r2 = sh.Cells[rowNumber, "AL"];
                    r2.Value = pm.Unity;

                    r2 = sh.Cells[rowNumber, "AM"];
                    r2.Value = cdm.Quantity;

                    r2 = sh.Cells[rowNumber, "AO"];
                    r2.Value = cdm.SalePrice;

                    r2 = sh.Cells[rowNumber, "AP"];
                    r2.Value = pm.ContributionMargin;

                    r2 = sh.Cells[rowNumber, "AQ"];
                    r2.Value = pm.CostPrice;

                    r2 = sh.Cells[rowNumber, "AR"];
                    r2.Value = cdm.SalePrice;

                    r2 = sh.Cells[rowNumber, "AS"];
                    r2.Value = pm.CostPrice * cdm.Quantity;

                    r2 = sh.Cells[rowNumber, "AT"];
                    r2.Value = cdm.SalePrice - (pm.CostPrice * cdm.Quantity);

                    r2 = sh.Cells[rowNumber, "AU"];
                    r2.Value = (cdm.SalePrice - (pm.CostPrice * cdm.Quantity)) / cdm.SalePrice * 100;

                    rowNumber++;
                }

                #endregion

                model.WriteInvoiceToBvDate = DateTime.Now;

            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToBv: " + ex.Message, true);
            } finally {
                if (wb != null) {
                    wb.Save();
                    wb.Close();
                }
                if (!excelStarted) {
                    exApp.Quit();
                }
            }
        }

        public static void WriteInvoiceToVrsp(CashSaleModel model) {
            Workbook wb = null;
            string sheetName = "Belege";
            string fileName = Path.Combine(@"T:\Admi\Ma\" + model.SaleDate.Year.ToString().Right(2) + @"\Vrsp" + model.SaleDate.Year.ToString().Right(2) + ".xlsx");
            bool excelStarted = ExcelIsStarted();
            myOffice.Excel.Application exApp = Office.GetExcelApplication();

            try {
                if (Tools.FileIsInUse(fileName) | (!File.Exists(fileName))) {
                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToVrsp: " + fileName + " ist geöffnet oder nicht vorhanden!", true);
                    return;
                }


                if (exApp != null) {

                }

                wb = exApp.Workbooks.Open(fileName);

                if (!Tools.SheetsExists(wb, sheetName)) {
                    return;
                }

                Worksheet sh = wb.Sheets[sheetName];
                int startRow = 4;
                bool weiter = false;
                DateTime invoiceDate;
                DateTime currentDate = model.SaleDate;

                Range r1 = sh.Cells[startRow, "A"];
                Range r2 = sh.Cells[startRow, "E"];
                

                while (weiter == false) {
                    r1 = sh.Cells[startRow, "A"];
                    r2 = sh.Cells[startRow, "E"];

                    if (r2.Value != null) {
                        if (r2.Value.ToString() == "Summe" || r2.Value.ToString() == "Differenz" || r2.Value.ToString() == "Saldo") {
                            DateTime.TryParse(r1.Value.ToString(), out invoiceDate);
                            if (invoiceDate.Month == model.SaleDate.Month && r2.Value.ToString() == "Summe") {
                                WriteToRow(startRow - 1, true, model, sh);
                                model.WriteInvoiceToVrspDate = DateTime.Now;
                                break;
                            }
                            if (r2.Value.ToString() == "Saldo") {
                                currentDate = invoiceDate;
                            }
                            startRow++;
                            continue;
                        }
                    }
                    if (r1.Value != null) {
                        DateTime.TryParse(r1.Value.ToString(), out invoiceDate);
                        currentDate = invoiceDate;
                        if (invoiceDate.Month <= model.SaleDate.Month) {
                            startRow++;
                            continue;
                        }
                        
                    }
                    if (r1.Value == null && r2.Value == null && currentDate.Month == model.SaleDate.Month) {
                        WriteToRow(startRow, false, model, sh);
                        model.WriteInvoiceToVrspDate = DateTime.Now;
                        break;
                    }
                    
                    startRow++;

                }
               


            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WriteInvoiceToLiqui: " + ex.Message, true);
            } finally {
                if (wb != null) {
                    wb.Save();
                    wb.Close();
                }
                if (!excelStarted) {
                    exApp.Quit();
                }
            }
        }

        private static void WriteToRow(int startRow, bool insertRow, CashSaleModel model, Worksheet sh) {
            Range aDatum;
            Range aFa;
            Range aGs;
            Range aGr;
            Range aKunde;
            Range aAr;
            Range aProject;
            Range aEinnahme;
            Range aFiBu;
            Range newRow = sh.Rows[startRow, Missing.Value];
            newRow.Select();
            newRow.Copy();
            newRow.Select();
            
            //newRow.PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationNone, SkipBlanks: false, Transpose: false);
            if (insertRow) {
                newRow.Insert(Shift: XlInsertShiftDirection.xlShiftDown);
                startRow++;
            }

            aDatum = sh.Cells[startRow, "A"];
            aFa = sh.Cells[startRow, "B"];
            aGs = sh.Cells[startRow, "C"];
            aGr = sh.Cells[startRow, "D"];
            aKunde = sh.Cells[startRow, "E"];
            aAr = sh.Cells[startRow, "G"];
            aProject = sh.Cells[startRow, "H"];
            aEinnahme = sh.Cells[startRow, "I"];
            aFiBu = sh.Cells[startRow, "M"];

            aDatum.Value = model.SaleDate.Date;
            aFa.Value = "Tp";
            aGs.Value = "Wk";
            aGr.Value = "Bv";
            aKunde.Value = model.OrgName;
            aAr.Value = model.InvoiceNo;
            aProject.Value = "0";
            aEinnahme.Value = model.GrossPrice;
            aFiBu.Value = "400 00";

            newRow.Font.Bold = true;
        }

        #endregion

        #region Word

        public static bool ExistingDocumentProperty(myOffice.Word.Document myDoc, string propertyName) {
            bool ret = false;
            try {
                string t1 = myDoc.CustomDocumentProperties[propertyName].Value.ToString();
                if (t1 != null) {
                    ret = true;
                }
            } catch {
                return false;
            }

            return ret;
        }

        public static void FillWordDocumentFields(myOffice.Word.Application appWord, myOffice.Word.Document myDoc, Extensions.DocType docType, string selType, Recipient myRecipient) {
            FillWordDocumentFields(appWord, myDoc, docType, selType, myRecipient, null);
        }

        public static void FillWordDocumentFields(myOffice.Word.Application appWord, myOffice.Word.Document myDoc, Extensions.DocType docType, string selType, Recipient myRecipient, InvoiceObject inv) {
            FillWordDocumentFields(appWord, myDoc, docType, selType, myRecipient, inv, null, null, null, false);
        }

        public static void FillWordDocumentFields(myOffice.Word.Application appWord, myOffice.Word.Document myDoc, Extensions.DocType docType, string selType,
            Recipient myRecipient, InvoiceObject inv, Organisation org,
            List<Beilage> beilagen, List<Person> mailCC, bool lineBreak) {
            try {

                #region Main

                if (Office.ExistingDocumentProperty(myDoc, "MailTo")) {
                    myDoc.CustomDocumentProperties["MailTo"].Delete();
                }

                myDoc.CustomDocumentProperties.Add("MailTo", false, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, myRecipient.EMail);

                Dictionary<string, string> myDict = new Dictionary<string, string>();
                Extensions.AddDictionayFields(myDict, "Recipient", myRecipient.Name);
                Extensions.AddDictionayFields(myDict, "Receipient", myRecipient.Name);
                if (lineBreak) {
                    Extensions.AddDictionayFields(myDict, "zuHandenMit", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden + (char)11 : ""));
                    Extensions.AddDictionayFields(myDict, "zuHanden", (myRecipient.CheckZuHanden ? myRecipient.ZuHanden + (char)11 : ""));
                    Extensions.AddDictionayFields(myDict, "RecipientPerson", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden + (char)11 : ""));
                    Extensions.AddDictionayFields(myDict, "ReceipientPerson", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden + (char)11 : ""));
                } else {
                    Extensions.AddDictionayFields(myDict, "zuHandenMit", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden : ""));
                    Extensions.AddDictionayFields(myDict, "zuHanden", (myRecipient.CheckZuHanden ? myRecipient.ZuHanden : ""));
                    Extensions.AddDictionayFields(myDict, "RecipientPerson", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden : ""));
                    Extensions.AddDictionayFields(myDict, "ReceipientPerson", (myRecipient.CheckZuHanden ? ", " + myRecipient.ZuHanden  : ""));
                }
                
                Extensions.AddDictionayFields(myDict, "Straße", myRecipient.Straße);
                Extensions.AddDictionayFields(myDict, "PlzOrt", myRecipient.PlzOrt);
                Extensions.AddDictionayFields(myDict, "Plz", myRecipient.Plz);
                Extensions.AddDictionayFields(myDict, "Ort", myRecipient.Ort);
                Extensions.AddDictionayFields(myDict, "LKZ", myRecipient.LKZ);
                Extensions.AddDictionayFields(myDict, "Anrede", myRecipient.Anrede);
                Extensions.AddDictionayFields(myDict, "H/F2", myRecipient.Anrede);
                Extensions.AddDictionayFields(myDict, "eMail", myRecipient.EMail);
                Extensions.AddDictionayFields(myDict, "FaxNr", myRecipient.Fax);
                Extensions.AddDictionayFields(myDict, "Empfänger", myRecipient.Name);

                Extensions.AddDictionayFields(myDict, "US", "us" + System.Environment.UserName.ToLower());
                Extensions.AddDictionayFields(myDict, "VeranlasserKZ", System.Environment.UserName.FirstCharBig());
                Extensions.AddDictionayFields(myDict, "VeranlasserIn", "in" + System.Environment.UserName.ToLower());
                Extensions.AddDictionayFields(myDict, "Veranlasser", UserPrincipal.Current.DisplayName);
                Extensions.AddDictionayFields(myDict, "BearbeiterKZ", Resources.Ma);
                Extensions.AddDictionayFields(myDict, "Datum", DateTime.Today.ToString(Extensions.tpDateFormatExtern));
                if (myDoc.Name.IndexOf(".") == 0) {
                    Extensions.AddDictionayFields(myDict, "DateiName", (myDoc != null ? Tools.Left(myDoc.Name, myDoc.Name.IndexOf(".")).Replace(GlobalVar.currentOrganisation.OrgName, (docType == Extensions.DocType.Angebot ? Extensions.TpKuerzel.Verk.GetStringValue() : Extensions.TpKuerzel.Kund.GetStringValue()) + @"\") : ""));
                } else {
                    if (myDoc.Name.IndexOf(".") > 0) {
                        Extensions.AddDictionayFields(myDict, "DateiName", Tools.Left(myDoc.Name, myDoc.Name.IndexOf(".")));
                    } else {
                        Extensions.AddDictionayFields(myDict, "DateiName", myDoc.Name);
                    }
                }
                Extensions.AddDictionayFields(myDict, "DatumBis", GetDatumBis().ToString(Extensions.tpDateFormatExtern));
                Extensions.AddDictionayFields(myDict, "Betreff", myRecipient.Betreff);
                Extensions.AddDictionayFields(myDict, "Thema", myRecipient.Betreff);

                #endregion

                #region Person

                if (GlobalVar.currentPerson != null) {

                }

                #endregion

                #region Beilagen

                if (beilagen != null) {
                    if (beilagen.Count > 0) {
                        bool hasBeilage = false;
                        int anzBeilagen = 0;
                        int currentBeilage = 1;
                        StringBuilder fileName = new StringBuilder();
                        foreach (Beilage bel in beilagen) {
                            if (bel.IsChecked) {
                                try {
                                    if (bel.FullFileName != null) {
                                        if (Office.ExistingDocumentProperty(myDoc, "File" + currentBeilage.ToString())) {
                                            myDoc.CustomDocumentProperties["File" + currentBeilage.ToString()].Delete();
                                        }
                                        myDoc.CustomDocumentProperties.Add("File" + currentBeilage.ToString(), false, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, bel.FullFileName);
                                    }
                                    if (!hasBeilage) {
                                        Extensions.AddDictionayFields(myDict, "BeilageText", "Beilage:");
                                        hasBeilage = true;
                                    }
                                    if (anzBeilagen > 0) {
                                        fileName.Append(", ");
                                    }
                                    fileName.Append(bel.BeilagenText);
                                    anzBeilagen++;
                                    currentBeilage++;
                                } catch (Exception ex) {
                                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFileds: " + ex.Message, true);
                                }
                            }
                        }


                        Extensions.AddDictionayFields(myDict, "BeilageDatei", fileName);

                        object toFind = "Beilage:";
                        myOffice.Word.Range myWRange = myDoc.Range();
                        myWRange = myDoc.Range();
                        if (myWRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                            myWRange.Font.Name = Extensions.tpFontBold;
                            myWRange.Font.Bold = 1;
                        }
                    } else {
                        try {
                            foreach (myOffice.Word.Bookmark bm in myDoc.Bookmarks) {
                                if (bm.Name == "BeilageText" || bm.Name == "BeilageDatei") {
                                    //bm.Range.Text = string.Empty;
                                    myDoc.Bookmarks[bm].Delete();
                                }
                            }

                            object toFind2 = "Beilage:";
                            myOffice.Word.Range myWRange2 = myDoc.Range();
                            myWRange2 = myDoc.Range();
                            if (myWRange2.Find.Execute(FindText: toFind2, MatchWholeWord: true)) {
                                myWRange2.Select();
                                myWRange2.Delete();
                                appWord.Selection.HomeKey(Unit: 5, Extend: 1);
                                appWord.Selection.EndKey(Unit: 5, Extend: 1);
                                appWord.Selection.Delete();

                            }

                            toFind2 = "BeilageDatei";
                            if (myWRange2.Find.Execute(FindText: toFind2, MatchWholeWord: true)) {
                                myWRange2.Select();
                                //appWord.Selection.EndKey(Unit: 5, Extend: 1);
                                //appWord.Selection.Delete();
                                myWRange2.Delete();
                            }

                        } catch (Exception ex) {
                            LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: " + ex.Message, true);
                        }
                    }
                }

                #endregion

                #region Kopie an

                if (mailCC != null) {
                    if (mailCC.Count > 0) {
                        bool hasmailCC = false;
                        int anzmailCC = 0;
                        int currentPerson = 1;
                        StringBuilder fileName2 = new StringBuilder();
                        foreach (Person pers in mailCC) {
                            if (pers.SendToThisPerson) {
                                try {
                                    if (Office.ExistingDocumentProperty(myDoc, "ccTo" + currentPerson.ToString())) {
                                        myDoc.CustomDocumentProperties["ccTo" + currentPerson.ToString()].Delete();
                                    }
                                    myDoc.CustomDocumentProperties.Add("ccTo" + currentPerson.ToString(), false, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, pers.EMail);

                                    if (!hasmailCC) {
                                        Extensions.AddDictionayFields(myDict, "KopieText", "Kopie:");
                                        hasmailCC = true;
                                    }
                                    if (anzmailCC > 0) {
                                        fileName2.Append(", ");
                                    }
                                    fileName2.Append((GetTitelName(pers.Titel1Key) != "" ? GetTitelName(pers.Titel1Key) + " " + pers.Vorname : pers.Vorname) + " " + pers.Zuname + " (" + pers.EMail + ")");
                                    anzmailCC++;
                                    currentPerson++;
                                } catch (Exception ex) {
                                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: " + ex.Message, true);
                                }
                            }
                        }

                        Extensions.AddDictionayFields(myDict, "KopiePerson", fileName2);

                        object toFind = "Kopie:";
                        myOffice.Word.Range myWRange = myDoc.Range();
                        myWRange = myDoc.Range();
                        if (myWRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                            myWRange.Font.Name = Extensions.tpFontBold;
                            myWRange.Font.Bold = 1;
                        }
                    } else {
                        try {
                            foreach (myOffice.Word.Bookmark bm in myDoc.Bookmarks) {
                                if (bm.Name == "KopieText" || bm.Name == "KopiePerson") {
                                    //bm.Range.Text = string.Empty;
                                    myDoc.Bookmarks[bm].Delete();
                                }
                            }

                            object toFind2 = "Kopie:";
                            myOffice.Word.Range myWRange2 = myDoc.Range();
                            myWRange2 = myDoc.Range();
                            if (myWRange2.Find.Execute(FindText: toFind2, MatchWholeWord: true)) {
                                myWRange2.Select();
                                myWRange2.Delete();
                                appWord.Selection.HomeKey(Unit: 5, Extend: 1);
                                appWord.Selection.EndKey(Unit: 5, Extend: 1);
                                appWord.Selection.Delete();

                            }

                            toFind2 = "KopiePerson";
                            if (myWRange2.Find.Execute(FindText: toFind2, MatchWholeWord: true)) {
                                myWRange2.Select();
                                //appWord.Selection.EndKey(Unit: 5, Extend: 1);
                                //appWord.Selection.Delete();
                                myWRange2.Delete();
                            }

                        } catch (Exception ex) {
                            LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: " + ex.Message, true);
                        }
                    }
                }

                #endregion

                #region Invoice

                try {
                    if (inv != null) {
                        StringBuilder myText = new StringBuilder();
                        myText.Append(inv.ZahlungsInfo);
                        bool empf = (inv.ReEmpfaenger != null ? true : false);

                        if (empf) {
                            if (inv.ReEmpfaenger.Left(2) == "Wg") {
                                inv.ReEmpfaenger = inv.ReEmpfaenger.Replace("Wg", "Wohnungseigentumsgemeinschaft ");
                            }
                        } else {
                            if (inv.Auftraggeber.Left(2) == "Wg") {
                                inv.Auftraggeber = inv.Auftraggeber.Replace("Wg", "Wohnungseigentumsgemeinschaft ");
                            }
                        }

                        Extensions.AddDictionayFields(myDict, "invEmpfänger", (empf ? inv.ReEmpfaenger : inv.Auftraggeber));
                        if (myDict.ContainsKey("Empfänger")) {
                            myDict.Remove("Empfänger");
                        }


                        Extensions.AddDictionayFields(myDict, "Empfänger", (empf ? inv.ReEmpfaenger.Trim() : inv.Auftraggeber.Trim()));
                        Extensions.AddDictionayFields(myDict, "zHdn", "");
                        if (empf & inv.RePersonCheck) {
                            if (myDict.ContainsKey("zHdn")) {
                                myDict.Remove("zHdn");
                            }
                            Extensions.AddDictionayFields(myDict, "zHdn", inv.RePerson);
                        }
                        if (!empf & inv.CheckAuftraggeberPerson) {
                            if (myDict.ContainsKey("zHdn")) {
                                myDict.Remove("zHdn");
                            }
                            Extensions.AddDictionayFields(myDict, "zHdn", inv.AuftraggeberHdn);
                        }
                        Extensions.AddDictionayFields(myDict, "invStrasse", (empf ? inv.ReStrasse : inv.AuftraggeberStrasse));
                        Extensions.AddDictionayFields(myDict, "invPlzOrt", (empf ? inv.RePlzOrt : inv.AuftraggeberPlzOrt));
                        Extensions.AddDictionayFields(myDict, "invMa", inv.Ma2);
                        Extensions.AddDictionayFields(myDict, "invReNr", inv.Rechnungsdatum.Year.ToString().Right(2) + inv.RechnungsNummer.ToString("000"));
                        Extensions.AddDictionayFields(myDict, "ReNr", inv.Rechnungsdatum.Year.ToString().Right(2) + inv.RechnungsNummer.ToString("000"));
                        Extensions.AddDictionayFields(myDict, "invDatum", inv.Rechnungsdatum.ToString(Extensions.tpDateFormatExtern));
                        if (inv.AFAbDatum.Value.Year > 1900) {
                            DateTime dt = (DateTime)inv.AFAbDatum;
                            Extensions.AddDictionayFields(myDict, "AuftragsDatum", String.Format(Resources.tmAuftragBestaetigung, dt.ToString(Extensions.tpDateFormatExtern)));
                        } else {
                            StringBuilder b1 = new StringBuilder();
                            //b1.Append(inv.AuftragsDatum.ToString(Extensions.tpDateFormatExtern) + " ");

                            if (inv.AufstragsArt == TpBaseObjects.Global.AuftragsArt.Persoenlich && inv.AFAuftragPersDatum.Value != new DateTime(1900, 1, 1)) {
                                b1.Append(inv.AFAuftragPersDatum.Value.ToString(Extensions.tpDateFormatExtern) + " Auftrag persönlich von " + inv.AFAuftragPersText);
                            }
                            if (inv.AufstragsArt == TpBaseObjects.Global.AuftragsArt.Telefonisch && inv.AFAuftragTelefonDatum.Value != new DateTime(1900, 1, 1)) {
                                b1.Append(inv.AFAuftragTelefonDatum.Value.ToString(Extensions.tpDateFormatExtern) + " Auftrag telefonisch von " + inv.AFAuftragTelefonText);
                            }
                            if (inv.ReBetreff != null) {
                                if (b1.Length > 0) {
                                    b1.Append(", ");
                                }
                                b1.Append(inv.ReBetreff);
                            }
                            Extensions.AddDictionayFields(myDict, "AuftragsDatum", b1.ToString());

                        }
                        if (inv.AFDurchfuehrungBis.Value.Day != inv.AFDurchfuehrungVon.Value.Day) {
                            DateTime dVon = (DateTime)inv.AFDurchfuehrungVon;
                            DateTime dBis = (DateTime)inv.AFDurchfuehrungBis;
                            if (inv.AFDurchfuehrungVon != new DateTime(1900, 1, 1)) {
                                Extensions.AddDictionayFields(myDict, "ArbeitsDatum", dVon.ToString(Extensions.tpDateFormatExtern) + " bis " + dBis.ToString(Extensions.tpDateFormatExtern));
                            } else {
                                Extensions.AddDictionayFields(myDict, "ArbeitsDatum", inv.ArbeitsDatum.ToString(Extensions.tpDateFormatExtern));
                            }
                        } else {
                            Extensions.AddDictionayFields(myDict, "ArbeitsDatum", inv.ArbeitsDatum.ToString(Extensions.tpDateFormatExtern));
                        }

                        Extensions.AddDictionayFields(myDict, "ProjektName", inv.Kunde);
                        Extensions.AddDictionayFields(myDict, "Projekt", inv.ProjektBezeichnung);


                        Extensions.AddDictionayFields(myDict, "PersKonto", inv.PersonenKonto.Replace(" ", ""));
                        Extensions.AddDictionayFields(myDict, "SachKonto", inv.SachKonto);
                        Extensions.AddDictionayFields(myDict, "Beilage", inv.Beilage);



                        if (inv.IsBusiness) {
                            if (inv.Ust == 0.0) {
                                myText.Append("\nUSt:\t");
                                myText.AppendLine(Resources.tmUstBauwesen);
                            }
                            if (inv.UID != null) {
                                myText.Append("UID:\t");
                                myText.Append(inv.UID);
                            }
                        }

                        if (inv.BeilageCheckLS | inv.BeilageCheckAP | inv.BeilageDateiCheck | inv.BeilageZusatzTextCheck | inv.Zahlschein) {
                            myText.Append("\nBeilage:\t");
                            myText.Append(inv.Beilage);
                        }

                        Extensions.AddDictionayFields(myDict, "EmpfSeite2", (inv.ReEmpfaenger == null ? inv.Auftraggeber : inv.ReEmpfaenger));
                        Extensions.AddDictionayFields(myDict, "ReNrSeite2", inv.Rechnungsdatum.Year.ToString().Right(2) + inv.RechnungsNummer.ToString("000"));

                        Extensions.AddDictionayFields(myDict, "ZahlungsInfo", myText.ToString());

                        if (Office.ExistingDocumentProperty(myDoc, "Sender")) {
                            myDoc.CustomDocumentProperties["Sender"].Delete();
                        }
                        myDoc.CustomDocumentProperties.Add("Sender", false, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, "neubauer@iqsol.at");

                    }
                } catch (Exception ex) {
                    LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: " + ex.Message, true);
                }

                #endregion

                #region Organisation

                if (org != null) {
                    myDict.Remove("Plz");
                    myDict.Remove("Ort");
                    myDict.Remove("LKZ");
                    Extensions.AddDictionayFields(myDict, "Prefix", org.Prefix);
                    Extensions.AddDictionayFields(myDict, "OrgName", org.OrgName);
                    Extensions.AddDictionayFields(myDict, "Zusätze", org.ZusätzeFW);
                    Extensions.AddDictionayFields(myDict, "Rechtsform", org.RechtsForm);
                    Extensions.AddDictionayFields(myDict, "Abteilung", org.Abteilung);
                    Extensions.AddDictionayFields(myDict, "Plz", org.Plz);
                    Extensions.AddDictionayFields(myDict, "Ort", org.Ort);
                    Extensions.AddDictionayFields(myDict, "LKZ", "");

                }

                #endregion

                SetWordBookmarks(myDoc, myDict);
                SetWordFields(myDoc, myDict);

                #region Ust und UID

                if (inv != null) {
                    myOffice.Word.Range myWordRange = myDoc.Range();
                    object toFind = "USt:";
                    if (myWordRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                        myWordRange.Font.Name = Extensions.tpFontBold;
                        myWordRange.Font.Bold = 1;
                    }
                    toFind = "UID:";
                    myWordRange = myDoc.Range();
                    if (myWordRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                        myWordRange.Font.Name = Extensions.tpFontBold;
                        myWordRange.Font.Bold = 1;
                    }
                    toFind = "Beilage:";
                    myWordRange = myDoc.Range();
                    if (myWordRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                        myWordRange.Font.Name = Extensions.tpFontBold;
                        myWordRange.Font.Bold = 1;
                    }
                } else {

                    myOffice.Word.Range myRange = myDoc.Range();
                    object findText = "us" + System.Environment.UserName.ToLower();
                    if (myRange.Find.Execute(FindText: findText, MatchWholeWord: true)) {
                        myRange.InsertAutoText();
                    }

                    myRange = myDoc.Range();
                    findText = "in" + System.Environment.UserName.ToLower();
                    if (myRange.Find.Execute(FindText: findText, MatchWholeWord: true)) {
                        myRange.InsertAutoText();
                    }
                }

                #endregion


            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: " + ex.Message, true);
            }
        }

        public static void FillWordDocumentFields(myOffice.Word.Application appWord, myOffice.Word.Document myDoc, CashSaleModel model) {
            StringBuilder details = new StringBuilder();

            if (Office.ExistingDocumentProperty(myDoc, "MailTo")) {
                myDoc.CustomDocumentProperties["MailTo"].Delete();
            }

            myDoc.CustomDocumentProperties.Add("MailTo", false, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, "EMail");

            try {
                Organisation org = OrganisationDataManager.LoadOrganisation(model.OrgKey);

                Dictionary<string, string> myDict = new Dictionary<string, string>();

                #region Address

                Extensions.AddDictionayFields(myDict, "Organisation", org.Prefix.AddSpace() + org.OrgName + " " + org.ZusätzeFW.AddSpace() + org.RechtsForm);
                Extensions.AddDictionayFields(myDict, "zuHanden", "");
                Extensions.AddDictionayFields(myDict, "Strasse", org.Straße);
                Extensions.AddDictionayFields(myDict, "PlzOrt", org.Plz + " " + org.Ort);

                #region Nachnahme

                if (model.PaymentMode == 3 && model.UseDeliveryAddress) {
                    Extensions.AddDictionayFields(myDict, "NNName1", model.DeliverName);
                    if (model.DeliverName2 != null && model.DeliverName2 != "") {
                        Extensions.AddDictionayFields(myDict, "NNName2", model.DeliverName2);
                    } else {
                        Extensions.AddDictionayFields(myDict, "NNName2", "");
                    }
                    Extensions.AddDictionayFields(myDict, "NNStrasse", model.DeliverStrasse);
                    Extensions.AddDictionayFields(myDict, "NNPlzOrt", model.DeliverPlz + " " + model.DeliverOrt);
                    Extensions.AddDictionayFields(myDict, "NNBetrag", model.GrossPrice.ToString("#,##0.00"));
                    Extensions.AddDictionayFields(myDict, "Betreff", "Bv" + model.SaleDate.Year.ToString().Right(2) + model.InvoiceNo.ToString("000"));
                }

                if (model.PaymentMode == 3 && !model.UseDeliveryAddress) {
                    Extensions.AddDictionayFields(myDict, "NNName1", org.OrgFullName);
                    Extensions.AddDictionayFields(myDict, "NNName2", "");
                    Extensions.AddDictionayFields(myDict, "NNStrasse", org.Straße);
                    Extensions.AddDictionayFields(myDict, "NNPlzOrt", org.Plz + " " + org.Ort);
                    Extensions.AddDictionayFields(myDict, "NNBetrag", model.GrossPrice.ToString("#,##0.00"));
                    Extensions.AddDictionayFields(myDict, "Betreff", "Bv" + model.SaleDate.Year.ToString().Right(2) + model.InvoiceNo.ToString("000"));
                }

                #endregion

                #region 2. Seite

                Extensions.AddDictionayFields(myDict, "NNSeite2", org.OrgName);
                Extensions.AddDictionayFields(myDict, "NNBetreff2", "Bv" + model.SaleDate.Year.ToString().Right(2) + model.InvoiceNo.ToString("000"));

                #endregion

                //}

                #endregion

                #region Main
                string zaHinweis = "Betrag dankend erhalten.";
                Extensions.AddDictionayFields(myDict, "ReNr", model.InvoiceNo.ToString(model.SaleDate.Year.ToString().Right(2) + "000"));
                Extensions.AddDictionayFields(myDict, "AuftragDatum", model.OrderDate.ToString(Extensions.tpDateFormatExtern));
                if (model.OrderDetail != null) {
                    Extensions.AddDictionayFields(myDict, "AuftragDetails", model.OrderDetail);
                } else {
                    Extensions.AddDictionayFields(myDict, "AuftragDetails", "");
                }
                Extensions.AddDictionayFields(myDict, "ReDatum", model.SaleDate.ToString(Extensions.tpDateFormatExtern));
                Extensions.AddDictionayFields(myDict, "ReUser", Contracts.MyUser.LoginName.Trim());
                Extensions.AddDictionayFields(myDict, "PaymentMode", GetPaymentMode(model.PaymentMode, model.GrossPrice * 0.02, model.GrossPrice * 0.98));
                Extensions.AddDictionayFields(myDict, "SumNetto", model.SalePrice.ToString("#,##0.00"));
                Extensions.AddDictionayFields(myDict, "SumUst", model.Taxes.ToString("#,##0.00"));
                Extensions.AddDictionayFields(myDict, "SumBrutto", model.GrossPrice.ToString("#,##0.00"));
                Extensions.AddDictionayFields(myDict, "Ust", (model.Taxes != 0 ? "20" : "0"));
                if (model.PaymentMode == 3 || model.PaymentMode == 4) {
                    zaHinweis = "";
                }
                Extensions.AddDictionayFields(myDict, "ZaHinweis", zaHinweis);
                #endregion

                #region Details

                CashSaleDetailsModel csdLast = model.MyDetails.Last();

                foreach (CashSaleDetailsModel csd in model.MyDetails) {
                    if (csd.Equals(csdLast)) {
                        details.Append(csd.ProductName + "\t" + csd.Unity + "\t" + csd.Quantity.ToString("#,##0.00") + "\t" + csd.Price.ToString("#,##0.00") + "\t" + csd.SalePrice.ToString("#,##0.00").Trim());
                    } else {
                        details.AppendLine(csd.ProductName + "\t" + csd.Unity + "\t" + csd.Quantity.ToString("#,##0.00") + "\t" + csd.Price.ToString("#,##0.00") + "\t" + csd.SalePrice.ToString("#,##0.00").Trim());
                    }
                }

                Extensions.AddDictionayFields(myDict, "Details", details.ToString());

                #endregion

                SetWordBookmarks(myDoc, myDict);

            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "FillWordDocumentFields: (CashSaleModel) " + ex.Message, true);
            }
        }

        public static string GetPaymentMode(int paymentMode, double skonto, double invoiceAmount) {
            string ret = "";
            PaymentModeObj pay = CashSaleDataManager.LoadPaymentType(paymentMode);
            if (pay != null) {
                ret = String.Format(pay.PaymentModeText, skonto.ToString("#,##0.00"), invoiceAmount.ToString("#,##0.00"));
            }
            return ret;
        }

        public static myOffice.Word.Document GetWordDocument(myOffice.Word.Application appWord, string fileName, string vorlage) {
            myOffice.Word.Document myDoc = null;
            try {
                if (vorlage != null | vorlage != string.Empty) {
                    myDoc = appWord.Documents.Add(Template: vorlage);
                    return myDoc;
                } else {
                    myDoc = appWord.Documents.Add();
                    return myDoc;
                }
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "GetWordDocument: " + ex.Message, true);
            }
            return myDoc;
        }

        public static myOffice.Word.Application GetWordApplication() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("WINWORD") > -1) {
                        return (myOffice.Word.Application)Marshal.GetActiveObject("Word.Application");
                    }
                }
                return new myOffice.Word.Application();
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "GetWordApplication: " + ex.Message, true);
            }
            return null;
        }

        public static void SetWordBookmarks(myOffice.Word.Document myDoc, Dictionary<string, string> myDict) {
            try {
                foreach (myOffice.Word.Bookmark bm in myDoc.Bookmarks) {
                    string tmName = bm.Name;
                    if (myDict.ContainsKey(tmName)) {
                        bm.Range.Text = myDict[tmName];
                    }
                }
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "SetWordBookmarks: " + ex.Message, true);
            }
        }

        public static void SetWordFields(myOffice.Word.Document myDoc, Dictionary<string, string> myDict) {
            try {
                foreach (KeyValuePair<string, string> myKey in myDict) {
                    object toFind = "<" + myKey.Key + ">>";
                    myOffice.Word.Range myWordRange = myDoc.Range();
                    if (myWordRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                        myWordRange.Text = myKey.Value;
                        continue;
                    }
                    toFind = "<" + myKey.Key + ">";
                    if (myWordRange.Find.Execute(FindText: toFind, MatchWholeWord: true)) {
                        myWordRange.Text = myKey.Value;

                    }
                }
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "SetWordFields: " + ex.Message, true);
            }
        }

        public static bool WordIsStarted() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach (Process proc in procs) {
                    if (proc.ProcessName.IndexOf("WINWORD") > -1) {
                        return true;
                    }
                }
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "WordIsStarted: " + ex.Message, true);
            }
            return false;
        }

        #endregion

    }
}

